from flask import Blueprint, request, make_response, jsonify, redirect

from app import db
from util.captcha.captcha import captcha
import json, random, time, requests
from util.myredis import r
from models.user import *
from werkzeug.security import generate_password_hash,check_password_hash

from utils.myjwt import myjwt

user_blue = Blueprint("userblue",__name__)

# 图形验证码
@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid,text,60)
    res = r.str_get(uuid)
    print(res)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

# 手机验证码验证
@user_blue.route('/mobilecode',methods=['POST'])
def mobilecode():
    data = json.loads(request.data)
    mobile = data['mobile']
    uuid = data['uuid']
    imagecode = data['imagecode']
    if not all([mobile,uuid,imagecode]):
        return jsonify({
            'code':400,
            'msg':"参数不完整"
        })
    red_imgcode = r.str_get(uuid)
    if red_imgcode:
        if red_imgcode.decode().lower() != imagecode.lower():
            return jsonify({
                'code':400,
                'msg':"图形验证码错误"
            })
        r.del_key(uuid)
    else:
        return jsonify({
            'code':400,
            'msg':"图形验证码已过期"
        })
    smscode = r.str_get(mobile)
    if smscode:
        return jsonify({
            'code':400,
            'msg':"一分钟只能发一次"
        })
    r.list_push('smsmobile',mobile)
    return jsonify({
        'code':200,
        'msg':"发送手机验证码成功"
    })

# 登录
@user_blue.route('/users_login',methods=['POST'])
def users_login():
    data = json.loads(request.data)
    password = data['password']
    mobile = data['mobile']
    mobile_code = data['mobile_code']
    if not all([mobile,mobile_code]):
        return jsonify({
            'code':400,
            'msg':"参数错误"
        })
    res = r.str_get(mobile)
    if res:
        if str(res.decode()) != str(mobile_code):
            return jsonify({
                'code':400,
                'msg':"手机验证码错误"
            })
        else:
            # r.del_key(mobile)
            use = Users.query.filter_by(mobile=mobile).first()
            if use:
                if check_password_hash(use.password,password):
                    data = {'data':{'id':use.id,'mobile':use.mobile,'password':use.password,'exp':int(time.time()+3600)}}
                    token = myjwt.jwt_encode(data)
                    return jsonify({
                        'code': 200,
                        'msg': "登陆成功",
                        'token':token,
                        'user_id':use.id
                    })
                else:
                    return jsonify({
                        'code':400,
                        'msg':"密码错误"
                    })
            else:
                return jsonify({
                    'code': 400,
                    'msg': "请先注册"
                })
    else:
        return jsonify({
            'code':400,
            'msg':"请先发送验证码"
        })

# 注册发送短信验证码
@user_blue.route('/register_code',methods=['POST'])
def register_code():
    data = json.loads(request.data)
    mobile = data['mobile']
    if not mobile:
        return jsonify({
            'code':400,
            'msg':'请输入手机号'
        })
    use = Users.query.filter_by(mobile=mobile).first()
    if use:
        return jsonify({
            'code': 400,
            'msg': "用户已存在"
        })
    red = r.str_get(mobile)
    if red:
        return jsonify({
            'code':400,
            'msg':"一分钟内不得重复发送"
        })
    r.list_push('smsmobile',mobile)
    return jsonify({
        'code':200,
        'msg':"短信验证码发送成功"
    })

# 注册
@user_blue.route('/users_register',methods=['POST'])
def users_register():
    data = json.loads(request.data)
    print(data)
    mobile = data['mobile']
    password = data['password']
    sms_code = data['sms_code']
    type = data['type']
    if not all([mobile,password,sms_code]):
        return jsonify({
            'code':400,
            'msg':"参数不完整"
        })
    mobile_code = r.str_get(mobile)
    if mobile_code:
        if mobile_code.decode() != sms_code:
            return jsonify({
                'code':400,
                'msg':"手机验证码错误"
            })
        else:
            r.del_key(mobile_code)
            use = Users.query.filter_by(mobile=mobile).first()
            if use:
                return jsonify({
                    'code':400,
                    'msg':"用户已存在"
                })
            else:
                pwd =generate_password_hash(password)
                add_use = Users(mobile=mobile,password=pwd,type=type)
                db.session.add(add_use)
                db.session.commit()
                return jsonify({
                    'code':200,
                    'msg':"注册成功"
                })
    else:
        return jsonify({
            'code':400,
            'msg':"请重新输入验证码"
        })

@user_blue.route('/getWBurl')
def getWBurl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({
        'code':200,
        'url':url
    })

@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}

    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # print("uid>>>>>>",uid)
    # 查询数据库中是否存在，如果存在用用户信息生成jwt token返回
    user = db.session.execute("select users.id,users.mobile from sf_login inner join users on sf_login.user_id=users.id where sf_login.uid='%s'" % (str(uid)))
    # user = json.loads(users)
    user = list(user)
    user_id = ""
    mobile = ""
    for i in user:
        user_id = i[0]
        mobile = i[1]
    if user:
        # 生成jwt
        # 返回jwt token
        token = myjwt.jwt_encode(data={"data": {"uid": user_id, "mobile":mobile, 'exp': int(time.time())}})
        return redirect("http://localhost:8080/update?token=" + token + "&userid=" + str(user_id))

    else:
        # 绑定
        return redirect("http://localhost:8080/bindModel?token=" + str(token) + "&uid=" + str(uid))


@user_blue.route('/bingMobile',methods=['POST'])
def bindmodel():
    # 接收参数
    data = json.loads(request.data)
    uid = data['uid']
    token = data['token']
    mobile = data['mobile']
    password = data['password']
    resa = Users.query.filter_by(mobile=mobile).first()
    if resa:
        lf_use = Sf_login(user_id=resa.id,webfrom='weibo',uid=uid,token=token)
        db.session.add(lf_use)
        db.session.commit()
        token = myjwt.jwt_encode(data={"data": {"uid": resa.id, "mobile": mobile, 'exp': int(time.time())}})
        return jsonify({"code": 200, "token": token, "userid": resa.id})
    else:
        try:
            # 加入用户表
            password = generate_password_hash(password)
            users = Users(mobile=mobile,password=password,type=0)
            db.session.add(users)
            db.session.commit()
            # 加入三方登录表
            lf_uses = Sf_login(user_id=users,webfrom='webbo',uid=uid,token=token)
            db.session.add(lf_uses)
            db.session.commit()
            token = myjwt.jwt_encode(data={"data": {"uid":users.id, "mobile": mobile, 'exp': int(time.time())}})
            return jsonify({"code": 200, "token": token, "userid": users.id})
        except Exception as e:
            print('>>>报错',e)
            return jsonify({'code':400,'msg':"错误"})
        # 返回jwt token




    # a = 'error': 'invalid_grant', 'error_code': 21325, 'request': '/oauth2/access_token', 'error_uri': '/oauth2/access_token', 'error_description': 'invalid authorization code:b12c58083c4a9b434fccaefa2eb08142'}